#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

enum class Status
{
    NEW,          // 初始连接状态
    RECONNECTING, // 正在重连
    CONNECTED,    // 连接成功
    DISCONNECTED, // 连接失败
    CLOSED        // 关闭连接
};

static const int default_sockfd = -1;
static const int default_retry_interval = 1;
static const int default_retries = 5;

class ClientConnection
{
public:
    ClientConnection(const std::string &serverip, uint16_t serverport)
        : _sockfd(default_sockfd)
        , _server_ip(serverip)
        , _server_port(serverport)
        , _status(Status::NEW)
        , _retry_interval(default_retry_interval)
        , _retries(default_retries)
    {}

    ~ClientConnection() {}

    Status ConnectionStatus() { return _status; }

    void Connect()
    {
        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(1);
        }

        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = ::htons(_server_port);
        ::inet_pton(AF_INET, _server_ip.c_str(), &server.sin_addr);

        int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            Disconnect();
            _status = Status::DISCONNECTED;
            return;
        }
        std::cout << "连接成功..." << std::endl;
        _status = Status::CONNECTED;
    }

    // 重连
    void Reconnect()
    {
        _status = Status::RECONNECTING;
        int cnt = 0;
        while (true)
        {
            Connect();
            if (_status == Status::CONNECTED)
                break;

            cnt++;
            if (cnt > _retries)
            {
                _status = Status::CLOSED;
                std::cout << "重连失败, 请检查你的网络..." << std::endl;
                break;
            }
            std::cout << "断线重连中, 重连次数: " << cnt << std::endl;
            sleep(_retry_interval);
        }
    }

    // 连接失败时: 关闭_sockfd
    void Disconnect()
    {
        if (_sockfd != default_sockfd)
        {
            ::close(_sockfd);
            _status = Status::CLOSED;
            _sockfd = default_sockfd;
        }
    }

    // 连接成功时: 进行通信
    void Process()
    {
        while (true)
        {
            std::string message = "hello server";
            ssize_t n = send(_sockfd, message.c_str(), message.size(), 0);
            if (n > 0)
            {
                char buffer[1024];
                int m = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
                if (m > 0)
                {
                    buffer[m] = 0;
                    std::cout << "server echo# " << buffer << std::endl;
                }
                else if (m == 0)
                {
                    _status = Status::DISCONNECTED;
                    std::cout << "服务器端掉线..." << std::endl;
                    break;
                }
                else 
                {
                    std::cerr << "recv error" << std::endl;
                    _status = Status::CLOSED;
                    break;
                }
            }
            else
            {
                std::cerr << "send error" << std::endl;
                _status = Status::CLOSED;
                break;
            }
            sleep(1);
        }
    }

private:
    int _sockfd;
    std::string _server_ip;
    uint16_t _server_port;

    Status _status;      // 连接状态
    int _retry_interval; // 重连的时间间隔
    int _retries;        // 重连的次数
};

class TcpClient
{
public:
    TcpClient(const std::string &serverip, uint16_t serverport)
        : _conn(serverip, serverport)
    {}

    ~TcpClient() {}

    void Execute()
    {
        while (true)
        {
            switch (_conn.ConnectionStatus())
            {
            case Status::NEW:
                _conn.Connect(); // 连接到来时: 进行连接
                break;
            case Status::CONNECTED:
                _conn.Process(); // 连接成功时: 进行通信
                break;
            case Status::DISCONNECTED:
                _conn.Reconnect(); // 连接失败时: 进行重连
                break;
            case Status::CLOSED:
                _conn.Disconnect(); // 连接关闭时: 关闭_sockfd
                return;
            default:
                // Do Nothing
                break;
            }
        }
    }

private:
    ClientConnection _conn;
};

void Usage(std::string process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

// ./tcp_client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    TcpClient client(server_ip, server_port);
    client.Execute();

    return 0;
}